/**
 * File: MaqStartController.java
 * Created by: mhaimel
 * Created on: 6 Jul 2009
 * CVS:  $Id: MaqStartController.java,v 1.2 2009/12/07 09:44:48 mhaimel Exp $
 */
package uk.ac.ebi.curtain.controller.maq.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.CRC32;

import uk.ac.ebi.curtain.controller.SimpleController;
import uk.ac.ebi.curtain.controller.maq.MaqBean;
import uk.ac.ebi.curtain.management.InterceptorInfo;
import uk.ac.ebi.curtain.utils.CurtainUncheckedException;
import uk.ac.ebi.curtain.utils.data.FileType;
import uk.ac.ebi.curtain.utils.data.ReadType;
import uk.ac.ebi.curtain.utils.file.FileInfo;

/**
 * @author mhaimel
 *
 */
public class MaqStartController extends SimpleController<File, MaqBean> {

	@Override
	protected MaqBean processData(File maqDir, InterceptorInfo info) {
		List<FileInfo> ctgList = new ArrayList<FileInfo>();
		ctgList.addAll(getContext().getArguments().getFiles(ReadType.Contig, FileType.getSequenceTypes()));
		for(ReadType rt : ReadType.values()){
			if(rt.equals(ReadType.Contig)){
				// already done
			} else if(rt.equals(ReadType.Short)){
				List<FileInfo> files = getContext().getArguments().getFiles(rt, FileType.getSequenceTypes());
				for(FileInfo fi : files){
					MaqBean bean = wrap(maqDir,ctgList,fi);
					submit(bean);
				}
			} else if(rt.equals(ReadType.ShortPaired)){
				List<FileInfo> files = getContext().getArguments().getFiles(rt, FileType.getSequenceTypes());
				for(FileInfo fi : files){
					MaqBean bean = wrap(maqDir,ctgList,fi);
					submit(bean);
				}
			} else {
				List<FileInfo> files = getContext().getArguments().getFiles(rt, FileType.getSequenceTypes());
				if(!files.isEmpty()){
					throw new CurtainUncheckedException("Logic not yet supported for Read type " + rt);
				}
			}
		}
		return null;
	}
	
	private MaqBean wrap(File workingDir, List<FileInfo> ctgFileArr, FileInfo ... readFileArr){
		MaqBean bean = new MaqBean();
		bean.getContigFiles().addAll(ctgFileArr);
		bean.setContigDir(workingDir);
		for(FileInfo read : readFileArr){
			bean.getReadFiles().add(read);
			bean.setReadDir(buildOutputFile(workingDir, read));
		}
		return bean;
	}
	
	private File buildOutputFile(File workingDir, FileInfo resource){
		CRC32 crc = new CRC32();
		crc.update(resource.getFile().getAbsolutePath().toString().getBytes());
		String hexString = Long.toHexString(crc.getValue());
		File readBaseDir = new File(workingDir,resource.getNameWithoutFilePostfix()+"_"+hexString);
		if(!readBaseDir.exists() && !readBaseDir.mkdirs()){
			throw new CurtainUncheckedException("Not able to create directory " + readBaseDir);
		}
		return readBaseDir;
	}

}
